
import { DICT_TYPE, getIntDictOptions } from "@/utils/dict";
import { Col, Form, Input, Modal, Row, Select, InputNumber, Flex, Radio, Spin, TreeSelect, message } from "antd";
import React, { useState, useEffect, useRef, useImperativeHandle, } from "react";
import * as menuApi from "@/api/system/menu/index";

const UserForm = ({ onRef, getList = Function }) => {
    const [treeData, setTreeData] = useState([]);
    const [show, setShow] = useState(false);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const menuType = Form.useWatch('menuType', form);

    /**@description 加载菜单树 */
    const loadMenuTree = async () => {
        const data = await menuApi.getMenuList();
        setTreeData(data?.treeData)
    }


    /**@description 表单布局 */
    const formItemLayout = {
        labelCol: {
            xs: {
                span: 24,
            },
            sm: {
                span: 4,
            },
        },
        wrapperCol: {
            xs: {
                span: 24,
            },
            sm: {
                span: 20,
            },
        },
    };

    /**@description 取消 */
    const onCanle = () => {
        setShow(false);
    }

    /**@description 添加|修改操作 */
    const open = async (type = String || undefined, id, parentId) => {
        setShow(true);
        loadMenuTree();
        form.resetFields();
        form.setFieldValue("type", "action." + type)




        if (type === "update") {
            form.setFieldValue("parentId", parentId);

            if (id) {
                try {
                    setLoading(true);
                    const data = await menuApi.getMenu(id);
                    form.setFieldsValue({
                        // parentId: parentId || undefined,
                        type: type || undefined,
                        ...data
                    });


                } catch (error) {

                } finally {
                    setLoading(false);
                }
            }
        } else if (type === "add") {
            // // 新增 
            form.setFieldValue("parentId", id);
        } else {
            form.setFieldValue("parentId", "0");
        }


    }

    /**@description 异步保存数据 */
    const createMenu = async (value) => {

        try {
            const data = await menuApi.createMenu(value);
            getList();
            onCanle();
        } catch (error) {

        } finally {

        }

    }

    /**@description 校验表单 */
    const validateForm = async () => {
        form.validateFields().then(res => {
            console.log("校验参数：", res)
            createMenu(res)
        })
    }

    /**@description 向外暴露方法 */
    useImperativeHandle(onRef, () => ({
        open
    }))

    /**@description form表单props配置 */
    const formProps = {
        form,
        initData: {
            type: undefined,
            parentId: "0",
            menuType: "1"
        }
    }

    useEffect(() => {
        show && loadMenuTree();
        !show && form.resetFields()
    }, [show])



    return (
        <>
            <Modal
                title="编辑"
                width={550}
                open={show}
                centered={true}
                destroyOnClose={true}
                onCancel={onCanle}
                onOk={validateForm}
            >
                <Spin spinning={loading}>
                    <Form
                        {...formItemLayout}
                        {...formProps}
                    >
                        <Row gutter={24}>
                            <Col span={24} style={{ display: "none" }} >
                                <Form.Item label="id" name="id">
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="上级菜单" name="parentId">
                                    <TreeSelect
                                        defaultValue={"0"}
                                        treeData={treeData}
                                        fieldNames={{
                                            label: "menuName",
                                            value: "id"
                                        }}
                                    />

                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="菜单名称" name="menuName">
                                    <Input placeholder="请输入菜单名称" />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item required={true} label="菜单类型" name="menuType">
                                    <Radio.Group
                                        block
                                        options={getIntDictOptions(DICT_TYPE.SYSTEM_MENU_TYPE)}
                                        defaultValue={"1"}
                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="菜单图标" name="menuIcon">
                                    <Input />
                                </Form.Item>
                            </Col>

                            <Col span={24}>
                                <Form.Item label="路由地址" tooltip="访问的路由地址，如：`user`。如需外网地址时，则以 `http(s)://` 开头" name="routerPath">
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="显示排序" name="sort">
                                    <InputNumber />
                                </Form.Item>
                            </Col>
                            {
                                menuType === "2" &&
                                <>
                                    <Col span={24}>
                                        <Form.Item tooltip="" label="组件名称" name="componentName">
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item label="组件地址" name="componentPath">
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item tooltip="Controller 方法上的权限字符，如：@PreAuthorize(`@ss.hasPermission('system:user:list')`)" label="权限标识" name="permissionMark">
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                </>
                            }

                            <Col span={24}>
                                <Form.Item label="菜单状态" name="status">
                                    <Radio.Group
                                        options={getIntDictOptions(DICT_TYPE.COMMON_STATUS)}

                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="显示状态" tooltip="选择隐藏时，路由将不会出现在侧边栏，但仍然可以访问" name="displayStatus">
                                    <Radio.Group
                                        block
                                        options={getIntDictOptions(DICT_TYPE.COMMON_STATUS)}
                                        defaultValue="dir"
                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="总是显示" tooltip="选择不是时，当该菜单只有一个子菜单时，不展示自己，直接展示子菜单" name="alwaysDisplay">
                                    <Radio.Group
                                        block
                                        options={[
                                            {
                                                label: "是",
                                                value: true
                                            },
                                            {
                                                label: "否",
                                                value: false
                                            }
                                        ]}
                                        defaultValue={true}
                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Spin>

            </Modal>
        </>
    )
}
export default UserForm;